package com.ken.myRule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

/**
 * <ul>
 * <li>Title: MyRandomRule</li>
 * <li>Description: TODO </li>
 * </ul>
 *
 * @author swc
 * @date 2021-08-27 16:11
 */
public class MyRandomRule extends AbstractLoadBalancerRule {

    private Map<Server,Integer>  serviceRequestMap = new HashMap<Server,Integer>();

    public MyRandomRule() {
    }

    //@SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {//当前线程是否已中断
                    return null;
                }

                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

                if(upList!=null){
                    upList.forEach((item)->{
                        if (!serviceRequestMap.containsKey(item.getPort()+"&"+item.getHost()+"&"+item.getId())){
                            serviceRequestMap.put(item,0);
                        }
                    });

                    Set<Server> servers = serviceRequestMap.keySet();

                    //单个服务请求阈值到了5 就进行下一个请求
                    for (Server ser : servers) {
                        if(serviceRequestMap.get(ser)<5){
                            serviceRequestMap.put(ser,serviceRequestMap.get(ser)+1);
                            server = ser;
                            break;
                        }else {
                            serviceRequestMap.put(ser,serviceRequestMap.get(ser)+1);
                        }
                    }

                    //如果所有服务请求都超过了五次 服务重新“注册”次数
                    if(server ==null){
                        serviceRequestMap.clear();
                    }


                    //int size = upList.size();
                    //this.chooseRandomInt(serverCount);
                }

                /*int index = this.chooseRandomInt(serverCount);
                server = (Server)upList.get(index);*/
                /*=======================================================算法改造================================================*/

                if (server == null) {
                    Thread.yield();//它让掉当前线程 CPU 的时间片，使正在运行中的线程重新变成就绪状态，并重新竞争 CPU 的调度权。它可能会获取到，也有可能被其他线程获取到。
                } else {
                    if (server.isAlive()) {
                        return server;
                    }
                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
